﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data;
using CommonTools;
using shop.Model;
using System.Threading.Tasks;

namespace shop.Bll
{

	/// <summary> 旺店通退款  </summary>
  	public class RefundDocBll // : BasePageBll<RefundDoc>
    {
        //public override string Title => "原始退款单";

        //public override bool EnableEditOnList => true;


        //public override bool RefreshOnOpen => true;

        //public override RefundDoc CopyItem(RefundDoc item)
        //{
        //    if (item == null)
        //        return null;

        //    var newItem = item.Clone();
        //    newItem.Id = 0;
        //    newItem.isdel = false;

        //    return newItem;
        //}

        //public override RefundDoc CreateItem()
        //{
        //    //return new RefundDoc() { isdel = false, FUser = UserBll.CurrentUser.Name, FTime = DateTime.Now, };
        //    return new RefundDoc() { isdel = false};
        //}

        //public override async Task<Result> DeleteItem(int id)
        //{
        //    await DB.FSql.Update<RefundDoc>()
        //        .Where(a => a.Id == id && a.isdel == false)
        //        .Set(a => a.isdel, true)
        //        .ExecuteAffrowsAsync();


        //    return new Result(true);
        //}


        //public override async Task<Result<int>> EditCell(string dataPropertyName, object value, RefundDoc data)
        //{
        //    if (data.Id == 0)
        //    {
        //        //data.FTime = await DB.FSql.GetTimeAsync();
        //        //data.FUser = UserBll.CurrentUser.Name;
        //        data.isdel = false;

        //        var nid = await DB.FSql.Insert(data)
        //            .ExecuteIdentityAsync();

        //        data.Id = (int)nid;
        //    }

        //    var dict = new Dictionary<string, object> { [dataPropertyName] = value };



        //    var dbRes = await DB.FSql.Update<RefundDoc>()
        //        .Where(a => a.Id == data.Id && a.isdel == false)
        //        .SetDto(dict)
        //        .ExecuteAffrowsAsync();


        //    return new Result<int>(true, "!", data.Id);
        //}

        //public override IEnumerable<DeclareColumn> GetColumns()
        //{
        //    return new[]
        //    {
        //        new DeclareColumn(nameof(RefundDoc.Id),"Id"){ Visible= false},
        //        new DeclareColumn(nameof(RefundDoc.Shop),"店铺"){ Width=260 },
          
        //    };
        //}

        //public override async Task<RefundDoc> GetItem(int id)
        //{
        //    return await DB.FSql.Select<RefundDoc>()
        //        .Where(a => a.isdel == false && a.Id == id)
        //        .ToOneAsync();
        //}


        #region 查询参数

        private string _shop;
        private string _user;

        #endregion

        ///// <summary> 查询ui </summary>
        //public override ControlBuilder GetUIBuilder()
        //{
        //    return new ControlBuilder()
        //        .Add<string>(ControlEnum.guanTextBox, "店铺名称", c => _shop= c)
        //        .Add<string>(ControlEnum.guanTextBox, "登录账号", c => _user = c)
        //        .AddQueryButton("查询");
        //}

        ///// <summary> 查询 </summary>
        //public override async Task<PageQueryResult<RefundDoc>> QueryPage(DocFilterParameter queryPara)
        //{
        //    var list = await DB.FSql.Select<RefundDoc>()
        //        .Where(a => a.isdel == false)
        //        .WhereIf(!string.IsNullOrEmpty(_shop), a => a.Shop.Contains(_shop) )
        //        //.WhereIf(!string.IsNullOrEmpty(_user), a => a.UserName.Contains(_user) )
        //        .Page(queryPara.PageNo, queryPara.PageSize)
        //        //.OrderBy(a => a.FTime)
        //        .OrderBy(a => a.Shop)
        //        .Count(out var c)
        //        .ToListAsync();


        //    return new PageQueryResult<RefundDoc>(true, null, list, c);
        //}



        //public override async Task<Result> SaveItem(RefundDoc item)
        //{
        //    if (item == null)
        //    {
        //        return new Result(false, "系统错误");
        //    }

        //    string err = string.Empty;
        //    if (string.IsNullOrEmpty(item.Shop))
        //    {
        //        err += "店铺名称不能为空!";
        //    }

        //    if (string.IsNullOrEmpty(err) == false)
        //    {
        //        return new Result(false, err);
        //    }

        //    item.isdel = false;
        //    //item.FTime = await DB.FSql.GetTimeAsync();
        //    //item.FUser = UserBll.CurrentUser.Name;

        //    if (item.Id <= 0)
        //    {
        //        var id = await DB.FSql.Insert(item)
        //            .ExecuteIdentityAsync();

        //        item.Id = (int)id;
        //    }
        //    else
        //    {
        //        await DB.FSql.Update<RefundDoc>()
        //            .SetSource(item)
        //            .ExecuteAffrowsAsync();
        //    }

        //    return new Result(true);
        //}



        public async Task<Result> ImportData(DataTable dt)
        {
            int plat = -1, shop = -1, no = -1, tid = -1, typeCol = -1, platSta = -1, sysSta = -1, failCol = -1, backStatusCol = -1, stageCol = -1, csCol = -1, modCol = -1, buyerCol = -1, refundAmntCol = -1, actAmnt = -1, nick = -1, reasonCol = -1, remarkCol = -1, logiName = -1, logoNo = -1, retime = -1, modifyCol = -1, crtTime = -1, success = -1, city = -1, addr = -1, userCol = -1, refuse = -1;


            int i = 0;
            foreach (DataColumn item in dt.Columns)
            {
                if (item.ColumnName == "平台") plat = i;
                if (item.ColumnName == "店铺") shop = i;
                if (item.ColumnName == "退款单号") no = i;
                if (item.ColumnName == "原始单号") tid = i;
                if (item.ColumnName == "类型") typeCol = i;
                if (item.ColumnName == "平台状态") platSta = i;
                if (item.ColumnName == "系统状态") sysSta = i;
                if (item.ColumnName == "递交失败原因") failCol = i;
                if (item.ColumnName == "退款回传状态") backStatusCol = i;
                if (item.ColumnName == "退款阶段") stageCol = i;
                if (item.ColumnName == "客服介入") csCol = i;
                if (item.ColumnName == "交易类型") modCol = i;
                if (item.ColumnName == "买家支付账号") buyerCol = i;
                if (item.ColumnName == "申请退款金额") refundAmntCol = i;
                if (item.ColumnName == "实际退款金额") actAmnt = i;
                if (item.ColumnName == "昵称") nick = i;
                if (item.ColumnName == "退款原因") reasonCol = i;
                if (item.ColumnName == "备注") remarkCol = i;
                if (item.ColumnName == "物流公司") logiName = i;
                if (item.ColumnName == "物流单号") logoNo = i;
                if (item.ColumnName == "退款时间") retime = i;
                if (item.ColumnName == "修改时间") modifyCol = i;
                if (item.ColumnName == "创建时间") crtTime = i;
                if (item.ColumnName == "退款成功时间") success = i;
                if (item.ColumnName == "原始单省市区") city = i;
                if (item.ColumnName == "原始单地址") addr = i;
                if (item.ColumnName == "操作人") userCol = i;
                if (item.ColumnName == "拒收退款标记") refuse = i;

                i++;
            }

            var data = dt.AsEnumerable()
                .Select(a => new RefundDoc()
                {
                    PlatForm = a.Field<string>(plat),
                    Shop = a.Field<string>(shop),
                    RefundNo = a.Field<string>(no),
                    Tid = a.Field<string>(tid),
                    RefundType = a.Field<string>(typeCol),
                    RefundStatus = a.Field<string>(platSta),
                    ProcessStatus = a.Field<string>(sysSta),
                    GiveFailReason = a.Field<string>(failCol),
                    BackStatus = a.Field<string>(backStatusCol),
                    RefundStage = a.Field<string>(stageCol),
                    cs_status = a.Field<string>(csCol),
                    guarantee_mode = a.Field<string>(modCol),
                    buyer = a.Field<string>(buyerCol),
                    RefundAmount = a.Field<string>(refundAmntCol).IsNull(0m),
                    ActualRefundAmount = a.Field<string>(actAmnt).IsNull(0m),
                    buyerNick = a.Field<string>(nick),
                    RefundReason = a.Field<string>(reasonCol),
                    Remarks = a.Field<string>(remarkCol),
                    logistics_name = a.Field<string>(logiName),
                    logistics_no = a.Field<string>(logoNo),
                    RefundTime = a.Field<string>(retime).IsNullDate(null),
                    ModifyTime = a.Field<string>(modifyCol).IsNullDate(null),
                    CreatedTime = a.Field<string>(crtTime).IsNullDate(null),
                    current_phase_timeout = a.Field<string>(success).IsNullDate(null),
                    OrigalCity = a.Field<string>(city),
                    OrigalAddr = a.Field<string>(addr),
                    Operator = a.Field<string>(userCol),
                    RefuseAccept = a.Field<string>(refuse),
                    isdel = false,

                    //Shop,
                    //RefundNo,
                    //Tid,
                    //RefundType,
                    //RefundStatus,
                    //ProcessStatus,
                    //GiveFailReason,
                    //BackStatus,
                    //RefundStage,
                    //cs_status,
                    //guarantee_mode,
                    //buyer,
                    //RefundAmount,
                    //ActualRefundAmount,
                    //buyerNick,
                    //RefundReason,
                    //Remarks,
                    //logistics_name,
                    //logistics_no,
                    //RefundTime,
                    //ModifyTime,
                    //CreatedTime,
                    //current_phase_timeout,
                    //OrigalCity,
                    //OrigalAddr,
                    //Operator,
                    //RefuseAccept,
                })
                .ToList();

            // 检查重复的, 将原先的标记删除 
            var tmp = data.Select(a => new IdTemp() { Name = a.RefundNo }).ToList();

            await DB.FSql.Select<RefundDoc>()
                .Where(a => a.isdel == false)
                .FromQuery(DB.FSql.Select<IdTemp>().WithMemory(tmp))
                .InnerJoin((a, b) => a.RefundNo == b.Name)
                .ToUpdate()
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();



            await DB.FSql.Insert(data).ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<IEnumerable<object>> QueryList(RefundRegQueryDto pr)
        {
            var begin = pr.Begin.Date;
            var end = pr.End.LastTimeOfDay();

            var list = await DB.FSql.Select<RefundDoc, RefundDocItem>()
                .InnerJoin((a,b) => a.Batch== b.Batch && a.RefundNo== b.RefundNo)
                .Where((a, b) => a.isdel == false)
                .Where((a, b) => a.FTime >= begin && a.FTime <= end)
                .WhereIf(!string.IsNullOrEmpty(pr.Shop), (a, b) => a.Shop == pr.Shop)
                .WhereIf(!string.IsNullOrEmpty(pr.platform_goods_id), (a, b) => b.goods_no.Contains(pr.platform_goods_id) )
                .WhereIf(!string.IsNullOrEmpty(pr.RefundNo), (a, b) => a.RefundNo == pr.RefundNo)
                .ToListAsync((a, b) => new
                {
                    a.DocFlag,
                    a.Id,
                    a.FTime,
                    a.Stock,
                    a.RefundNo,
                    a.trade_no,
                    a.logistics_name,
                    a.logistics_no,
                    b.goods_no,
                    a.RefundReason,
                    b.remarks,
                    a.IsSendMessage,
                });

            
            return list
                .Select(a => new
                {
                    Id = a.Id,
                    抓取时间= a.FTime,
                    分类= a.DocFlag== "sh" ? "退换补发单" : "补偿退款单",
                    仓库= a.Stock,
                    退款单号 = a.RefundNo,
                    订单编号= a.trade_no,
                    //退款原因 = a.RefundReason,
                    物流公司 = a.logistics_name,
                    物流单号 = a.logistics_no,
                    货品编号 = a.goods_no,
                    退换原因= a.RefundReason,
                    备注= a.remarks,
                    是否发送消息= a.IsSendMessage ? "已发送" : "",
                })
                .OrderBy(a=> a.抓取时间)
                .ToList();

        }


        public async Task<Result> DeleteItems(List<int> list)
        {
            if(list == null || list.Count ==0)
            {
                return new Result(true);
            }


            var tmp = list.Select(a => new IdTemp() { Id = a }).ToList();

            await DB.FSql.Select<RefundDoc>()
                .Where(a => a.isdel == false)
                .FromQuery(DB.FSql.Select<IdTemp>().WithMemory(tmp))
                .InnerJoin((a, b) => a.Id == b.Id)
                .ToUpdate()
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            return new Result(true);
        }




    }




}



 
